package ui

import (
	"lnzw/common/proto/cs_gen"
	"lnzw/common/stringutils"
	"lnzw/engine/log"
	"lnzw/server/test/test_fyne/test_3/data"
	"lnzw/server/test/test_fyne/test_3/transport"
	"strconv"

	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/widget"
	"go.uber.org/zap"
)

type MapCreateUI struct {
	UIBase
	fyne.Container
	WidthLabel  *widget.Label
	HeightLabel *widget.Label
	WidthEntry  *widget.Entry
	HeightEntry *widget.Entry
	Ensure      *widget.Button
}

func NewMapCreateUI(app fyne.App, parentWindow fyne.Window) *MapCreateUI {
	w := app.NewWindow("创建地图")
	w.Resize(fyne.NewSize(230, 200))
	w.SetFixedSize(true)
	w.CenterOnScreen()
	ui := &MapCreateUI{
		UIBase: UIBase{
			App:    app,
			Window: w,
		},
	}
	ui.UIBase.Container = &ui.Container
	ui.Init()
	w.SetPadded(false)
	w.SetContent(&ui.Container)
	w.Show()
	return ui
}

func (m *MapCreateUI) Init() {
	m.WidthLabel = widget.NewLabel("宽:")
	m.WidthLabel.Move(fyne.NewPos(10, 20))
	m.Add(m.WidthLabel)
	m.WidthEntry = widget.NewEntry()
	m.WidthEntry.Resize(fyne.NewSize(150, 40))
	m.WidthEntry.Move(fyne.NewPos(40, 20))
	textChange(m.WidthEntry)
	m.Add(m.WidthEntry)
	m.HeightLabel = widget.NewLabel("高:")
	m.HeightLabel.Move(fyne.NewPos(10, 80))
	m.Add(m.HeightLabel)
	m.HeightEntry = widget.NewEntry()
	m.HeightEntry.Resize(fyne.NewSize(150, 40))
	m.HeightEntry.Move(fyne.NewPos(40, 70))
	textChange(m.HeightEntry)
	m.Add(m.HeightEntry)
	m.Ensure = widget.NewButton("确定", func() {
		width, _ := strconv.Atoi(m.WidthEntry.Text)
		height, _ := strconv.Atoi(m.HeightEntry.Text)
		msg, err := transport.DefaultSyncSend("", data.MapMgrCatalog, &cs_gen.ReqCreateMap{Width: int32(width), Height: int32(height)})
		if err != nil {
			log.Error("actor.SyncSend error", zap.Error(err))
			return
		}
		GlobalEventMgr.Dispatch(EventType_CreateMap, msg)
		m.GetWindow().Close()
	})
	m.Ensure.Resize(fyne.NewSize(150, 40))
	m.Ensure.Move(fyne.NewPos(40, 120))
	m.Add(m.Ensure)
}

func textChange(entry *widget.Entry) {
	entry.OnChanged = func(s string) {
		if !stringutils.IsNumber(s) {
			if len(s) == 0 {
				return
			}
			entry.Text = stringutils.RemoveNonNumber(s)
			return
		}
	}
}
